package com.gdth.bank.activity.setting;

import java.io.File;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.StringParam;
import com.gdth.bank.bean.DownloadBean;
import com.gdth.bank.bean.XtBbGxBean;
import com.gdth.bank.presenter.XtBbGxPresenter;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.view.XtBbGxView;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.http.callback.DownLoadCallback;
import com.gdth.http.listener.UIProgressListener;
import com.gdth.http.listener.impl.UIProgressListenerImpl;
import com.gdth.http.method.EngDNS;
import com.gdth.http.method.ProgressHelper;
import com.gdth.http.method.httpsUtils;
import com.gdth.utils.GsonUtil;
import com.gdth.utils.ToolUtil;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.dialog.DialogConfig;
import com.gdth.widget.dialog.DialogProgressBar;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class BbxxActivity  extends BaseActivity implements XtBbGxView{
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
    @ViewInject(id=R.id.header_btn_right) TextView txt_header_right;
    
	@ViewInject(id=R.id.bbxx_button, click="bbgxClick") Button bbxx_button;
	@ViewInject(id=R.id.bbxx_bbmc) TextView txt_bbmc;
	@ViewInject(id=R.id.bbxx_bbh) TextView txt_bbh;
	
	DialogConfig config;
	
	private DialogProgressBar mProgressBar;
	
	XtBbGxPresenter  mXtBbGxPresenter;
	String mc,apkname,verName, path;
	int verCode;
	
	private static final OkHttpClient client = new OkHttpClient.Builder()
	    .connectTimeout(1000, TimeUnit.MINUTES)
	    .readTimeout(1000, TimeUnit.MINUTES)
	    .writeTimeout(1000, TimeUnit.MINUTES)
		.dns(new EngDNS())
	    .sslSocketFactory(httpsUtils.getSSLSocketFactory())
		.hostnameVerifier(httpsUtils.getHostnameVerifier())
	    .build();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_bbxx);
		
		initView();
	}
	
	public void initView() {
		txt_header_title.setText(getResources().getString(R.string.param1));
		txt_header_right.setVisibility(View.GONE);
		txt_bbmc.setText(getResources().getString(R.string.param1));
		txt_bbh.setText(getResources().getString(R.string.param2) + AppUtil.getVerName(this));
		mXtBbGxPresenter = new XtBbGxPresenter(this);

		mProgressBar = new DialogProgressBar(this, getResources().getString(R.string.param3));
		
		config = new DialogConfig(this, getResources().getString(R.string.param4), true, downloadClickListener);
	}
	
	public void bbgxClick(View arg0){
		mXtBbGxPresenter.getBbGx(getResources().getString(R.string.param5));
	}
	
	@Override
	public void getXtBbGxData(XtBbGxBean mXtBbGxBean) {
		// TODO Auto-generated method stub
		mc = mXtBbGxBean.getMc();
		apkname = mXtBbGxBean.getApkmc();
		verName = mXtBbGxBean.getBbmc();
		verCode = Integer.valueOf(mXtBbGxBean.getBbh());
		
		if (BankApplication.versionCode < verCode) {
			path = mXtBbGxBean.getDz();
			config.setCancelable(false);
			config.show();
		} else {
			this.showMessage(getResources().getString(R.string.param6));
		}
	}
	
	private OnClickListener downloadClickListener = new  OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			config.dismiss();
			boolean is=panduanqx();
			if(is==false){
				showMessage(getResources().getString(R.string.param7));
			}else{
				DownloadBean bean = new DownloadBean();
				bean.setName(apkname);
				bean.setScms(0);
				bean.setCjsj(new Date());
				bean.setPath(path);
				bean.setGnmk(5);
				bean.setLocalPath(ToolUtil.getFilePath(apkname));
				mProgressBar.show();
				mProgressBar.setCancelable(false);
				download(bean);
			}
		}
	};
	
	private void download(DownloadBean bean) {
        //这个是非ui线程回调，不可直接操作UI
		String content = GsonUtil.getGson().toJson(bean);
        
		String url = BankApplication.mInstance.url + "bank/fileDownLoadOperate!downLoadByName.do?content="+content;
		
        //这个是ui线程回调，可直接操作UI
        final UIProgressListener uiProgressResponseListener = new UIProgressListenerImpl(mProgressBar.mProgressBar);

        //构造请求
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request).enqueue(new DownLoadCallback(mHandler));
    }
	
	private Handler mHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub

			mProgressBar.dismiss();
			if (msg.what == 101) {
				
				Bundle bundle = msg.getData();
				String path = bundle.getString("path");
				
		        Intent intent = new Intent(Intent.ACTION_VIEW); 
//		        Intent intent = new Intent(Intent.ACTION_VIEW); 
		        if (Build.VERSION.SDK_INT >= 24) {
		        	 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				        Uri url=FileProvider.getUriForFile(BbxxActivity.this, "com.jph.takephoto.fileprovider", new File(path));
				        intent.setDataAndType(url, "application/vnd.android.package-archive");
		        }else{
		        	intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");  
		        }
			    startActivity(intent);
			}
			
			
			return false;
		}
	});

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		BaseToast.getInstance().ShowSystemToast(this, msg);
	}
	
	// 判断存储权限
	public boolean panduanqx() {
		PackageManager pm = getPackageManager();
		boolean permission = (PackageManager.PERMISSION_GRANTED == pm
				.checkPermission("android.permission.READ_EXTERNAL_STORAGE", "com.gdth.bank"));
		if (permission) {
			return true;
		}
		return false;

}
}
